package fr.znight.chacunsatv.utils;

import java.util.List;
import fr.znight.chacunsatv.R;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AppAdapter extends ArrayAdapter<AppObject> {

	protected List<AppObject> l;
	protected Context context;
	
	public AppAdapter(Context context, int textViewResourceId, List<AppObject> objects) {
		super(context, textViewResourceId, objects);
		this.l = objects;
		this.context = context;
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return l.size();
	}
	
	@Override
	public AppObject getItem(int position) {
		// TODO Auto-generated method stub
		return l.get(position);
	}
	
	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View item = convertView;
		
		if (item == null) {
	        LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        item = vi.inflate(R.layout.itemgrid, null);
	    }

	    if (l.get(position) != null) {

	        TextView list_title = (TextView) item.findViewById(R.id.txt_item_grid);
	        ImageView list_image = (ImageView) item.findViewById(R.id.img_item_grid);

	        if (list_title != null) {
	            list_title.setText(l.get(position).getAppName());
	        }

	        if (list_image != null) {
	            list_image.setImageDrawable(l.get(position).getIcon());
	        }
	        
	        item.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					Intent intent = context.getPackageManager().getLaunchIntentForPackage(l.get(position).getPackageName()); 
					intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
					intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
					context.startActivity(intent);
				}

			});
	    }

		
		return item;
	}
	
}
